<?php
	require_once('paths.inc');
	require_once(INCLUDE_PATH.'constants.inc');
	require_once('page.inc');
	require_once(DB_PATH.'db.inc');	
	
	require_once('security.inc');
	require_once('utils.inc');	
	require_once('server_validations.inc');	
	require_once('time.inc');
	
	session_start();

	check_permissions(CT_PERM_COMENZI);
	$id_client = $_SESSION['user_logat']->id_client;
	
    function clearAdreseOwners($adrese) {
        foreach ($adrese as $adr) {
            $adr->id_owner = CT_NOT_SAVED_YET;
            $adr->status = CT_ADDRESS_NEW;
        }
                        
        return $adrese;    
    }

	function getActeValue($act1, $act2) {
		$rez = null;
		if ($act1 == null)
			if ($act2 == null)
                $rez = CT_ACT_NENECESAR;
            else
                $rez = CT_ACT_NENECESAR_SI_EXISTENT;
		else {
			if ($act2 == null)
				$rez = CT_ACT_NECESAR_SI_NEEXISTENT;
			else 
				$rez = CT_ACT_NECESAR_SI_EXISTENT;
		}
		return $rez;
	}
	
	$db = db_connect();

	if (isset($_POST['post_comanda'])) {					
		// luare din post
		$id_firma_sol = (int) $_POST['id_firma_sol'];
		$nr_factura_sol = $_POST['nr_factura_sol'];
        $nr_comanda_sol = $_POST['nr_comanda_sol'];
		$nr_referinta_sol = $_POST['nr_referinta_sol'];
		$suma_sol = prepareNumberForServer($_POST['suma_sol']);
		$taxe_supl_to_sol = prepareNumberForServer($_POST['taxe_supl_to_sol']);
		$penaliz_from_sol = prepareNumberForServer($_POST['penaliz_from_sol']);
		$data_tr_acte_sol = getDateForServer($_POST['data_tr_acte_sol']);
		$suma_totala_sol = prepareNumberForServer($_POST['suma_totala_sol']);
		$moneda_sol = $_POST['moneda_sol'];
		$id_contact_sol = $_POST['id_contact_sol'];
		$data_scadenta_sol = getDateForServer($_POST['data_scadenta_sol']);
        $data_factura_sol = getDateForServer($_POST['data_factura_sol']);
        $zile_scadenta_sol = prepareNumberForServer($_POST['zile_scadenta_sol']);
		$zile_scadenta_exec = prepareNumberForServer($_POST['zile_scadenta_exec']);
		$coment_sol = $_POST['coment_sol'];
		
		// Checkboxes SOL
		
		$_cmr_sol = getActeValue($_POST['_cmr_sol'], $_POST['_cmr_sol2']);
		$_factura_sol = getActeValue($_POST['_factura_sol'], $_POST['_factura_sol2']);
		$_carnet_tir_sol = getActeValue($_POST['_carnet_tir_sol'], $_POST['_carnet_tir_sol2']);
		$_decl_vamala_sol = getActeValue($_POST['_decl_vamala_sol'], $_POST['_decl_vamala_sol2']);
		$_alte_acte_sol = getActeValue($_POST['_alte_acte_sol'], $_POST['_alte_acte_sol2']);
		
		$_text_alte_acte_sol = $_POST['_text_alte_acte_sol'];
		
		$id_firma_exec = (int) $_POST['id_firma_exec'];
		$nr_factura_exec = $_POST['nr_factura_exec'];
		$nr_comanda_exec = $_POST['nr_comanda_exec'];
        
        // Verificare TVA;
        if (isset($_POST['tva_inclus_exec']))
            $tva_inclus_exec = CT_TVA_INCLUS_EXEC;
        else
            $tva_inclus_exec = CT_TVA_NEINCLUS_EXEC;
            
		$suma_exec = prepareNumberForServer($_POST['suma_exec']);
		$taxe_supl_from_exec = prepareNumberForServer($_POST['taxe_supl_from_exec']);
		$penaliz_to_exec = prepareNumberForServer($_POST['penaliz_to_exec']);		
		$data_primirii_acte_exec = getDateForServer($_POST['data_primirii_acte_exec']);
		$suma_totala_exec = prepareNumberForServer($_POST['suma_totala_exec']);
		$moneda_exec = $_POST['moneda_exec'];

        if (!isset($_POST['id_contact_exec'])) 
        	$id_contact_exec = $_POST['id_contact_exec_aux_hidden'];
        else
            $id_contact_exec = $_POST['id_contact_exec'];
            
		$data_scadenta_exec = getDateForServer($_POST['data_scadenta_exec']);
		$data_factura_exec = getDateForServer($_POST['data_factura_exec']);
		$coment_exec = $_POST['coment_exec'];
		$_cmr_exec = $_POST['_cmr_exec'];
		// Checkboxes SOL
		$_cmr_exec = getActeValue($_POST['_cmr_exec'], $_POST['_cmr_exec2']);
		$_factura_exec = getActeValue($_POST['_factura_exec'], $_POST['_factura_exec2']);
		$_carnet_tir_exec = getActeValue($_POST['_carnet_tir_exec'], $_POST['_carnet_tir_exec2']);
		$_decl_vamala_exec = getActeValue($_POST['_decl_vamala_exec'], $_POST['_decl_vamala_exec2']);
		$_alte_acte_exec = getActeValue($_POST['_alte_acte_exec'], $_POST['_alte_acte_exec2']);
		$_text_alte_acte_exec = $_POST['_text_alte_acte_exec'];
				
        $data_comenzii = getDateForServer($_POST['data_comenzii']);
		$data_comanda_sol = getDateForServer($_POST['data_comanda_sol']);
		$tel_sofer = $_POST['tel_sofer'];
		$nume_sofer = $_POST['nume_sofer'];
		$nr_inmatriculare = $_POST['nr_inmatriculare'];
		$fel_camion = $_POST['fel_camion'];
		$fel_marfa = $_POST['fel_marfa'];
		$tonaj = prepareNumberForServer($_POST['tonaj']);
		$data_incarcarii = getDateForServer($_POST['data_incarcarii']);
		$data_descarcarii = getDateForServer($_POST['data_descarcarii']);
        $alte_conditii = $_POST['alte_conditii'];		
		                             
        // Verificare TVA;
        if (isset($_POST['interna_externa']))
            $interna_externa = CT_COMANDA_INTERNA;
        else
            $interna_externa = CT_COMANDA_EXTERNA;
                
        $nr_km = prepareNumberForServer($_POST['nr_km']);
        $status = $_POST['status'];
		
		//***************************************server side validations
		$_SESSION['wrong_ids'] = array();
        
        // MINIM 1 adresa de incarcare si una de descarcare.
        if (count($_SESSION['comanda']->adrese_incarcare) < 1) {
            $_SESSION['wrong_ids']['incarcare'] = 1;
            $mesaj_aditional .= LANG_Trebuie_cel_putin_o_adresa_de_incarcare.'<br />';
        }
        if (count($_SESSION['comanda']->adrese_descarcare) < 1) {
            $_SESSION['wrong_ids']['descarcare'] = 1;
            $mesaj_aditional .= LANG_Trebuie_cel_putin_o_adresa_de_descarcare.'<br />';
        }
			
		// Verificare firme diferite!!!
		if ($id_firma_sol == $id_firma_exec) {
			$_SESSION['wrong_ids']['id_firma_sol'] = 1;
			$_SESSION['wrong_ids']['id_firma_exec'] = 1;
		}
		
		// verificare id-uri firma sol
		$q = "select id from firme 
				where 
					id = $id_firma_sol AND id_client = $id_client";
		$result = $db->query($q);								

		if ($result === FALSE) {
            // TODO: error treating
		}
		else {												
			$count = 0;
			while($row = $result->fetch(PDO::FETCH_ASSOC)) {
				$count++;
			}
		}

		if ($count != 1) {
			$_SESSION['wrong_ids']['id_firma_sol'] = 1;
			$_SESSION['wrong_ids']['id_contact_sol'] = 1;
		}		
		
		// verificare id-uri firma exec
		$q = "select id from firme
				where 
					id = $id_firma_exec AND firme.id_client = $id_client";
//        echo $q;
		$result = $db->query($q);								

		if ($result === FALSE) {
            // TODO: error treating
		}	
		else {												
			$count = 0;
			while($row = $result->fetch(PDO::FETCH_ASSOC)) {
				$count++;
			}
		}
		if ($count != 1) {
			$_SESSION['wrong_ids']['id_firma_exec'] = 1;
			$_SESSION['wrong_ids']['id_contact_exec'] = 1;
		}		
		
		//Asignare campuri
        $aux = filter_var($id_firma_sol, FILTER_VALIDATE_INT);
		if ($aux === FALSE)
			$_SESSION['wrong_ids']['id_firma_sol'] = 1;
		$_SESSION['comanda']->id_firma_sol = $id_firma_sol;
		
			
		if (!validPrintable($nr_factura_sol, 0, CT_MAX_NR_FACTURA_LENGTH)) {
			$_SESSION['wrong_ids']['nr_factura_sol'] = 1;
		}
		$_SESSION['comanda']->nr_factura_sol = $nr_factura_sol;
			
			
		if (!validPrintable($nr_comanda_sol, 0, CT_MAX_NR_COMANDA_LENGTH)) {
			$_SESSION['wrong_ids']['nr_comanda_sol'] = 1;
		}
		$_SESSION['comanda']->nr_comanda_sol = $nr_comanda_sol;
         
            
        if (!validPrintable($nr_referinta_sol, 1, CT_MAX_NR_COMANDA_LENGTH)) {
            $_SESSION['wrong_ids']['nr_referinta_sol'] = 1;
        }
        $_SESSION['comanda']->nr_referinta_sol = $nr_referinta_sol;
		
			
		$aux = filter_var($suma_sol, FILTER_VALIDATE_FLOAT);
		if ($aux === false) {
			$_SESSION['wrong_ids']['suma_sol'] = 1;
		}
		$_SESSION['comanda']->suma_sol = $suma_sol;
			
		
		$aux = filter_var($taxe_supl_to_sol, FILTER_VALIDATE_FLOAT);
		if ($aux === FALSE && $taxe_supl_to_sol != '')
			$_SESSION['wrong_ids']['taxe_supl_to_sol'] = 1;
		$_SESSION['comanda']->taxe_supl_to_sol = $taxe_supl_to_sol;
		
		
		$aux = filter_var($penaliz_from_sol, FILTER_VALIDATE_FLOAT);
		if ($aux === FALSE && $penaliz_from_sol != '')
			$_SESSION['wrong_ids']['penaliz_from_sol'] = 1;
		$_SESSION['comanda']->penaliz_from_sol = $penaliz_from_sol;
			
			
		$aux = checkServerDate($data_tr_acte_sol);
		if ($aux == FALSE && $data_tr_acte_sol != '')
			$_SESSION['wrong_ids']['data_tr_acte_sol'] = 1;
		$_SESSION['comanda']->data_tr_acte_sol = $data_tr_acte_sol;
			
            
        $suma_totala_sol_mai_mica = false;
        $suma_totala_sol_mai_mare = false;
		$aux2 = ($suma_totala_sol == $_SESSION['comanda']->suma_sol + $_SESSION['comanda']->taxe_supl_to_sol - $_SESSION['comanda']->penaliz_from_sol);
        $aux = filter_var($suma_totala_sol, FILTER_VALIDATE_FLOAT);
		if ($aux === FALSE || $aux2 === FALSE)
			$_SESSION['wrong_ids']['suma_totala_sol'] = 1;

		if ($_SESSION['comanda']->suma_totala_sol > $suma_totala_sol)
            $suma_totala_sol_mai_mica = true;
        if ($_SESSION['comanda']->suma_totala_sol < $suma_totala_sol)
            $suma_totala_sol_mai_mare = true;
        $_SESSION['comanda']->suma_totala_sol = $suma_totala_sol;
		
			
		$aux = filter_var($moneda_sol, FILTER_VALIDATE_INT);
		if ($aux === FALSE || $moneda_sol < 0 || $moneda_sol > count($currencies))
			$_SESSION['wrong_ids']['moneda_sol'] = 1;
		$_SESSION['comanda']->moneda_sol = $moneda_sol;
		
		
        // NU MAI TREBUIE	
		//$aux = filter_var($id_contact_sol, FILTER_VALIDATE_INT);
//		if ($aux === FALSE)
//			$_SESSION['wrong_ids']['id_contact_sol'] = 1;
//		else 
//			$_SESSION['comanda']->id_contact_sol = $id_contact_sol;
		
			
		$aux = checkServerDate($data_scadenta_sol);
		if ($aux == FALSE && $data_scadenta_sol != '')
			$_SESSION['wrong_ids']['data_scadenta_sol'] = 1;
		$_SESSION['comanda']->data_scadenta_sol = $data_scadenta_sol;
            
        $aux = filter_var($zile_scadenta_sol, FILTER_VALIDATE_FLOAT);
        if ($aux === FALSE)
            $_SESSION['wrong_ids']['zile_scadenta_sol'] = 1;
        $_SESSION['comanda']->zile_scadenta_sol = $zile_scadenta_sol;    
		
			
		$aux = checkServerDate($data_factura_sol);
		if ($aux == FALSE && $data_factura_sol != '')
			$_SESSION['wrong_ids']['data_factura_sol'] = 1;
		$_SESSION['comanda']->data_factura_sol = $data_factura_sol;
		
        if (!validPrintable($coment_sol, 0, CT_MAX_TEXT_LENGTH))
			$_SESSION['wrong_ids']['coment_sol'] = 1;
		$_SESSION['comanda']->coment_sol = $coment_sol;		
			
			
		$aux = filter_var($_cmr_sol, FILTER_VALIDATE_INT);
		if ($aux === FALSE)
			$_SESSION['wrong_ids']['_cmr_sol'] = 1;
		$_SESSION['comanda']->_cmr_sol = $_cmr_sol;
			
			
		$aux = filter_var($_factura_sol, FILTER_VALIDATE_INT);
		if ($aux === FALSE)
			$_SESSION['wrong_ids']['_factura_sol'] = 1;
		$_SESSION['comanda']->_factura_sol = $_factura_sol;
			
			
		$aux = filter_var($_carnet_tir_sol, FILTER_VALIDATE_INT);
		if ($aux === FALSE)
			$_SESSION['wrong_ids']['_carnet_tir_sol'] = 1;
		$_SESSION['comanda']->_carnet_tir_sol = $_carnet_tir_sol;
			
			
		$aux = filter_var($_decl_vamala_sol, FILTER_VALIDATE_INT);
		if ($aux === FALSE)
			$_SESSION['wrong_ids']['_decl_vamala_sol'] = 1;
		$_SESSION['comanda']->_decl_vamala_sol = $_decl_vamala_sol;
			
			
		$aux = filter_var($_alte_acte_sol, FILTER_VALIDATE_INT);
		if ($aux === FALSE)
			$_SESSION['wrong_ids']['_alte_acte_sol'] = 1;
		$_SESSION['comanda']->_alte_acte_sol = $_alte_acte_sol;
		
			
		if (!validPrintable($_text_alte_acte_sol, 0, CT_MAX_TEXT_LENGTH))
			$_SESSION['wrong_ids']['_text_alte_acte_sol'] = 1;
		$_SESSION['comanda']->_text_alte_acte_sol = $_text_alte_acte_sol;
		
			
		$aux = filter_var($id_firma_exec, FILTER_VALIDATE_INT);
		if ($aux === FALSE)
			$_SESSION['wrong_ids']['id_firma_exec'] = 1;
		$_SESSION['comanda']->id_firma_exec = $id_firma_exec;
			
			
		if (!validPrintable($nr_factura_exec, 0, CT_MAX_NR_FACTURA_LENGTH)) 
			$_SESSION['wrong_ids']['nr_factura_exec'] = 1;
		$_SESSION['comanda']->nr_factura_exec = $nr_factura_exec;
			
            
		if (!validPrintable($nr_comanda_exec, 1, CT_MAX_NR_COMANDA_LENGTH))
			$_SESSION['wrong_ids']['nr_comanda_exec'] = 1;
		$_SESSION['comanda']->nr_comanda_exec = $nr_comanda_exec;
			
        $_SESSION['comanda']->tva_inclus_exec = $tva_inclus_exec;
            
		$aux = filter_var($suma_exec, FILTER_VALIDATE_FLOAT);
		if ($aux === FALSE)
			$_SESSION['wrong_ids']['suma_exec'] = 1;
		$_SESSION['comanda']->suma_exec = $suma_exec;
			
			
		$aux = filter_var($taxe_supl_from_exec, FILTER_VALIDATE_FLOAT);
		if ($aux === FALSE && $taxe_supl_from_exec != '')
			$_SESSION['wrong_ids']['taxe_supl_from_exec'] = 1;
		$_SESSION['comanda']->taxe_supl_from_exec = $taxe_supl_from_exec;
			
			
		$aux = filter_var($penaliz_to_exec, FILTER_VALIDATE_FLOAT);
		if ($aux === FALSE && $penaliz_to_exec != '')
			$_SESSION['wrong_ids']['penaliz_to_exec'] = 1;
		$_SESSION['comanda']->penaliz_to_exec = $penaliz_to_exec;
		
			
		$aux = checkServerDate($data_primirii_acte_exec);
		if ($aux == FALSE  && $data_primirii_acte_exec != '')
			$_SESSION['wrong_ids']['data_primirii_acte_exec'] = 1;
		$_SESSION['comanda']->data_primirii_acte_exec = $data_primirii_acte_exec;
			
			
        $suma_totala_exec_mai_mare = false;
		$aux2 = ($suma_totala_exec == $_SESSION['comanda']->suma_exec + $_SESSION['comanda']->taxe_supl_from_exec - $_SESSION['comanda']->penaliz_to_exec);
        $aux = filter_var($suma_totala_exec, FILTER_VALIDATE_FLOAT);		
		if ($aux === FALSE || $aux2 === FALSE)
			$_SESSION['wrong_ids']['suma_totala_exec'] = 1;
		
        if ($_SESSION['comanda']->suma_totala_exec > $suma_totala_exec)
            $suma_totala_exec_mai_mica = true;
        if ($_SESSION['comanda']->suma_totala_exec < $suma_totala_exec)
            $suma_totala_exec_mai_mare = true;
        $_SESSION['comanda']->suma_totala_exec = $suma_totala_exec;
			
			
		$aux = filter_var($moneda_exec, FILTER_VALIDATE_INT);
		if ($aux === FALSE || $moneda_exec < 0 || $moneda_exec > count($currencies))
			$_SESSION['wrong_ids']['moneda_exec'] = 1;
		else 
			$_SESSION['comanda']->moneda_exec = $moneda_exec;
			
		// NU MAI TREBUIE
		//$aux = filter_var($id_contact_exec, FILTER_VALIDATE_INT);
        //var_dump($id_contact_exec);
//        if ($aux === FALSE)
//			$_SESSION['wrong_ids']['id_contact_exec'] = 1;
//		else 
//			$_SESSION['comanda']->id_contact_exec = $id_contact_exec;
			
			
		$aux = checkServerDate($data_scadenta_exec);
		if ($aux == FALSE && $data_scadenta_exec != '')
			$_SESSION['wrong_ids']['data_scadenta_exec'] = 1;
		$_SESSION['comanda']->data_scadenta_exec = $data_scadenta_exec;

        $aux = filter_var($zile_scadenta_exec, FILTER_VALIDATE_FLOAT);
        if ($aux === FALSE)
            $_SESSION['wrong_ids']['zile_scadenta_exec'] = 1;
        $_SESSION['comanda']->zile_scadenta_exec = $zile_scadenta_exec;    
			
			
		$aux = checkServerDate($data_factura_exec);
		if ($aux == FALSE && $data_factura_exec != '')
			$_SESSION['wrong_ids']['data_factura_exec'] = 1;
		$_SESSION['comanda']->data_factura_exec = $data_factura_exec;		
		
			
        if (!validPrintable($coment_exec, 0, CT_MAX_TEXT_LENGTH)) 
			$_SESSION['wrong_ids']['coment_exec'] = 1;
		$_SESSION['comanda']->coment_exec = $coment_exec;
			
			
		$aux = filter_var($_cmr_exec, FILTER_VALIDATE_INT);
		if ($aux === FALSE)
			$_SESSION['wrong_ids']['_cmr_exec'] = 1;
		$_SESSION['comanda']->_cmr_exec = $_cmr_exec;
			
			
		$aux = filter_var($_factura_exec, FILTER_VALIDATE_INT);
		if ($aux === FALSE)
			$_SESSION['wrong_ids']['_factura_exec'] = 1;
		$_SESSION['comanda']->_factura_exec = $_factura_exec;
			
			
		$aux = filter_var($_carnet_tir_exec, FILTER_VALIDATE_INT);
		if ($aux === FALSE)
			$_SESSION['wrong_ids']['_carnet_tir_exec'] = 1;
		$_SESSION['comanda']->_carnet_tir_exec = $_carnet_tir_exec;
			
			
		$aux = filter_var($_decl_vamala_exec, FILTER_VALIDATE_INT);
		if ($aux === FALSE)
			$_SESSION['wrong_ids']['_decl_vamala_exec'] = 1;
		$_SESSION['comanda']->_decl_vamala_exec = $_decl_vamala_exec;
			
			
		$aux = filter_var($_alte_acte_exec, FILTER_VALIDATE_INT);
		if ($aux === FALSE)
			$_SESSION['wrong_ids']['_alte_acte_exec'] = 1;
		$_SESSION['comanda']->_alte_acte_exec = $_alte_acte_exec;
		
		if (!validPrintable($_text_alte_acte_exec, 0, CT_MAX_TEXT_LENGTH))
			$_SESSION['wrong_ids']['_text_alte_acte_exec'] = 1;
		$_SESSION['comanda']->_text_alte_acte_exec = $_text_alte_acte_exec;
		
			
		$aux = checkServerDate($data_comenzii);
		if ($aux == FALSE)
			$_SESSION['wrong_ids']['data_comenzii'] = 1;
		$_SESSION['comanda']->data_comenzii = $data_comenzii;
            
            
        $aux = checkServerDate($data_comanda_sol);
        if ($aux == FALSE)
            $_SESSION['wrong_ids']['data_comanda_sol'] = 1;
        $_SESSION['comanda']->data_comanda_sol = $data_comanda_sol;
            
			
		if (!validPrintable($tel_sofer, 0, CT_MAX_TEXT_LENGTH)) 
			$_SESSION['wrong_ids']['tel_sofer'] = 1;
		$_SESSION['comanda']->tel_sofer = $tel_sofer;
		
			
		if (!validPrintable($nume_sofer, 0, CT_MAX_TEXT_LENGTH)) 
			$_SESSION['wrong_ids']['nume_sofer'] = 1;
		$_SESSION['comanda']->nume_sofer = $nume_sofer;
		
			
		if (!validPrintable($nr_inmatriculare, 0, CT_MAX_NR_INMATRICULARE_LENGTH)) 
			$_SESSION['wrong_ids']['nr_inmatriculare'] = 1;
		$_SESSION['comanda']->nr_inmatriculare = $nr_inmatriculare;
		
			
		if (!validPrintable($fel_camion, 1, CT_MAX_FEL_CAMION_LENGTH)) 
			$_SESSION['wrong_ids']['fel_camion'] = 1;
		$_SESSION['comanda']->fel_camion = $fel_camion;
		

		if (!validPrintable($alte_conditii, 0, CT_MAX_TEXT_LENGTH)) 
			$_SESSION['wrong_ids']['alte_conditii'] = 1;
        $_SESSION['comanda']->alte_conditii = $alte_conditii;
            
        $_SESSION['comanda']->interna_externa = $interna_externa;
        
        $_SESSION['comanda']->nr_km = $nr_km;
        
        if (!validPrintable($status, 0, CT_MAX_TEXT2_LENGTH)) 
            $_SESSION['wrong_ids']['status'] = 1;
        $_SESSION['comanda']->status = $status;
					
        // VERIFICA SUMELE FATA DE PLATI / INCASARI
        $platit = 0;
        $incasat = 0;
        foreach($_SESSION['comanda']->plati as $plata) {
            if ($plata->tip = CT_PLATA_INCASARE)
                $platit += $plata->suma;
            else
                $incasat += $plata->suma;
        }
        
        if ($suma_totala_exec_mai_mica == true && $platit > $_SESSION['comanda']->suma_totala_exec) {
            $_SESSION['wrong_ids']['suma_totala_exec'] = 1;
            notice_msg('LANG_suma_exec_trebuie_sa_fie_cel_putin_egala_cu_platile_efectuate');
        }
        
        if ($suma_totala_exec_mai_mare == true && $platit > 0)
            $_SESSION['comanda']->stare_plata_exec = CT_COMANDA_PLATITA_PARTIAL;
            
        if ($suma_totala_sol_mai_mica == true && $incasat > $_SESSION['comanda']->suma_totala_sol) {
            $_SESSION['wrong_ids']['suma_totala_sol'] = 1;
            notice_msg('LANG_suma_sol_trebuie_sa_fie_cel_putin_egala_cu_incasarile_efectuate');
        }
        
        if ($suma_totala_sol_mai_mare == true && $incasat > 0)
            $_SESSION['comanda']->stare_plata_sol = CT_COMANDA_INCASATA_PARTIAL;
				
		if (count($_SESSION['wrong_ids']) > 0) {
			notice_msg($mesaj_aditional . LANG_Campurile_rosii_trebuiesc_completate_corect, 'add_comanda.php');			
		}
		else
			unset($_SESSION['wrong_ids']);
			
		if ($_SESSION['comanda']->id_comanda == CT_NOT_SAVED_YET) { 
			try {
				$aux = $_SESSION['comanda']->queryInsert($db);	
				if ($aux != CT_QUERY_FAILED) {
					//unset($_SESSION['comanda']);
                    notice_msg('LANG_Comanda_a_fost_adaugata_cu_succes', 'show_comenzi.php');    
                }
			}
            catch (QueryNumarComandaException $e) {
                $_SESSION['wrong_ids']['nr_comanda_exec'] = 1;
                notice_msg('LANG_Campurile_rosii_trebuiesc_completate_corect', 'add_comanda.php');                
            }
            catch (QueryNumarReferintaException $e) {
                $_SESSION['wrong_ids']['nr_referinta_sol'] = 1;
                notice_msg('LANG_Campurile_rosii_trebuiesc_completate_corect', 'add_comanda.php');                
            }
			catch (QueryInsertComandaException $e) {
				redirectOnError(CT_ADD_COMANDA_INSERT_COMANDA);                           
			}
		}
		else {
			//edit firma
			try {                
				$aux = $_SESSION['comanda']->queryUpdate($db);	
				if ($aux != CT_QUERY_FAILED) {
					//unset($_SESSION['comanda']);
                    notice_msg('LANG_Comanda_a_fost_modificata_cu_succes', 'show_comenzi.php');    
                }
			}
            catch (QueryNumarComandaException $e) {
                $_SESSION['wrong_ids']['nr_comanda_exec'] = 1;
                notice_msg('LANG_Numarul_de_comanda_unic', 'add_comanda.php');                
            }
            catch (QueryNumarReferintaException $e) {
                $_SESSION['wrong_ids']['nr_referinta_sol'] = 1;
                notice_msg('LANG_Numarul_de_referinta_unic', 'add_comanda.php');                
            }
			catch (QueryUpdateComandaException $e) {
				redirectOnError(CT_ADD_COMANDA_UPDATE_COMANDA);
			}
			catch (QueryWrongVersionException $e) {
				notice_msg('LANG_Datele_pe_care_lucrati_au_fost_modificate', 'add_comanda.php');
			}
		}		
		
	}
	else {		
		
		if (isset($_SESSION['wrong_ids']) && !empty($_SESSION['wrong_ids'])) {			
			if (count($_SESSION['wrong_ids']) > 0) {
				$wrong_ids = $_SESSION['wrong_ids'];				
				unset($_SESSION['wrong_ids']);
			}
		}
		else {
		
			if (!isset($_SESSION['comanda'])) $_SESSION['comanda'] = null;
			
            if (isset($_GET['id']))
				$id = $_GET['id'];
				
            if (isset($_GET['idd']))
                $idd = $_GET['idd'];
                    
			if (isset($_GET['dash_id']))
				$dash_id = $_GET['dash_id'];	
				
			if (isset($id) && !empty($id)) {
				//edit				
				try {
					$_SESSION['comanda'] = Comanda::queryLoadById($db, $id, $id_client);
                    
                    if (!has_permission(CT_PERM_COMENZI_DUPA_CONFIRMARE)) {
                        $confirmari = 0;
                        //var_dump($_SESSION['comanda']->adrese_incarcare);
                        foreach($_SESSION['comanda']->adrese_incarcare as $adresa)
                            if ($adresa->data_efectiva != '') {
                                $confirmari = 1;
                                break;   
                            }
                            
                        
                        if ($confirmari == 0)
                            foreach($_SESSION['comanda']->adrese_descarcare as $adresa)
                            if ($adresa->data_efectiva != '') {
                                $confirmari = 1;
                                break;   
                            }
                        
                        if ($confirmari != 0)
                            notice_msg(LANG_Nu_aveti_dreptul_sa_editati_o_comanda_confirmata
                                        , 'view_comanda.php?id=' . $_SESSION['comanda']->id_comanda);
                    }
				}
				catch (QueryLoadComandaException $e) {
					redirectOnError(CT_ADD_COMANDA_LOAD_BY_ID_COMANDA);
				}
				catch (QueryLoadFirmaException $e) {
					redirectOnError(CT_ADD_COMANDA_LOAD_BY_ID_COMANDA);
				}
			}
			else {
				//add new
                if (isset($idd) && !empty($idd)) {
                	
                // duplicate comanda
                    try {
						unset($_SESSION['comanda']);
                        $_SESSION['comanda'] = Comanda::queryLoadById($db, $idd, $id_client);
                        $_SESSION['comanda']->id_comanda = CT_NOT_SAVED_YET;
                        $_SESSION['comanda']->data_comenzii = date('Y-m-d');
                        $_SESSION['comanda']->data_comanda_sol = date('Y-m-d');
                        $_SESSION['comanda']->adrese_incarcare = clearAdreseOwners($_SESSION['comanda']->adrese_incarcare);
                        $_SESSION['comanda']->adrese_descarcare = clearAdreseOwners($_SESSION['comanda']->adrese_descarcare);
                        $_SESSION['comanda']->adrese_vama_import = clearAdreseOwners($_SESSION['comanda']->adrese_vama_import);
                        $_SESSION['comanda']->adrese_vama_export = clearAdreseOwners($_SESSION['comanda']->adrese_vama_export);
                        $_SESSION['comanda']->stare_incasare_sol = CT_COMANDA_NEINCASATA;
                        $_SESSION['comanda']->stare_plata_exec = CT_COMANDA_NEPLATITA;
                        $_SESSION['comanda']->plati = array();
                    }
                    catch (QueryLoadComandaException $e) {
                        redirectOnError(CT_ADD_COMANDA_LOAD_BY_ID_COMANDA);
                    }
                }
                else 
                if (isset($dash_id) && !empty($dash_id)) {
                    try {
                        unset($_SESSION['comanda']);
                        $dash = Dashboard::queryGetByID($db, $id_client, $dash_id);
                        $id_user = $_SESSION['user_logat']->id_user;
                        $_SESSION['comanda'] = new Comanda($id_client, $id_user);
                        $_SESSION['comanda']->moneda_sol = $_SESSION['user_logat']->moneda;
                        $_SESSION['comanda']->moneda_exec = $_SESSION['user_logat']->moneda;
                        $_SESSION['comanda']->interna_externa = $_SESSION['user_logat']->comanda_interna_externa;
                        
                        try {
                            $setari_client = SetariClient::queryLoadSetariClient($db, $id_client);
                            $_SESSION['comanda']->zile_scadenta_sol = $setari_client->zile_scadenta_sol;
                            $_SESSION['comanda']->zile_scadenta_exec = $setari_client->zile_scadenta_exec;
                        }
                        catch (QueryLoadSetariException $e) {
                            redirectOnError(CT_ADD_COMANDA_LOAD_SETARI_CLIENT_BY_ID);
                        }
                        catch (QuerySettingsNotExistException $e) {
                            redirectOnError(CT_ADD_COMANDA_LOAD_SETARI_CLIENT_BY_ID);
                        }
                        
                        $adresaIncarcare = new Address(CT_ADRESA_COMANDA, null, $dash->oras_plecare, null, null, $dash->tara_plecare, null, CT_ADRESA_COMANDA_INCARCARE);    
                        $adresaIncarcare->data = $dash->data_plecare;
                        
                        $adresaDescarcare = new Address(CT_ADRESA_COMANDA, null, $dash->oras_sosire, null, null, $dash->tara_sosire, null, CT_ADRESA_COMANDA_DESCARCARE);    
                        $adresaDescarcare->data = $dash->data_sosire;
                        
                        $_SESSION['comanda']->adrese_incarcare[] = $adresaIncarcare;
                        $_SESSION['comanda']->adrese_descarcare[] = $adresaDescarcare;
                        
                        $_SESSION['comanda']->nr_km = $dash->km;
                        
                        if ($dash->tip == CT_DASHBOARD_CAMION) {
                            $_SESSION['comanda']->suma_exec = $dash->pret_total;
                            $_SESSION['comanda']->suma_totala_exec = $dash->pret_total;
                        }
                        else {
                            $_SESSION['comanda']->suma_sol = $dash->pret_total;
                            $_SESSION['comanda']->suma_totala_sol = $dash->pret_total;
                        }
                    }
                    catch (QueryLoadDashboardException $e) {
                        redirectOnError(CT_LOAD_DASH);
                    }
                }
                else {
				    $id_user = $_SESSION['user_logat']->id_user;
				    $_SESSION['comanda'] = new Comanda($id_client, $id_user); 
				    
				    //monedele implicite ale solicitantului si executantului sunt cele default din user
				    $_SESSION['comanda']->moneda_sol = $_SESSION['user_logat']->moneda;
                    $_SESSION['comanda']->moneda_exec = $_SESSION['user_logat']->moneda;
				    $_SESSION['comanda']->interna_externa = $_SESSION['user_logat']->comanda_interna_externa;

				    try {
						$setari_client = SetariClient::queryLoadSetariClient($db, $id_client);
						$_SESSION['comanda']->zile_scadenta_sol = $setari_client->zile_scadenta_sol;
						$_SESSION['comanda']->zile_scadenta_exec = $setari_client->zile_scadenta_exec;
				    }
				    catch (QueryLoadSetariException $e) {
						redirectOnError(CT_ADD_COMANDA_LOAD_SETARI_CLIENT_BY_ID);
				    }
				    catch (QuerySettingsNotExistException $e) {
						redirectOnError(CT_ADD_COMANDA_LOAD_SETARI_CLIENT_BY_ID);
				    }
                }
				try {
                    $arr = Comanda::getNrComandaAndNrReferintaNou($db, $id_client);
                    $_SESSION['comanda']->nr_comanda_exec = $arr[0];
                    $_SESSION['comanda']->nr_referinta_sol = $arr[1];
                }
                catch (QueryGetNrComandaNou $e) {
                    redirectOnError(CT_GET_NR_COMANDA_AND_NR_REFERINTA_NOU);
                }
			}
			$_SESSION['comanda'] = (object)$_SESSION['comanda'];
		}
		
	if ($_SESSION['comanda']->id_comanda == CT_NOT_SAVED_YET)
	    html_header("LANG_Adauga_comanda", null, "add_comanda");
    else 
        html_header("LANG_Modifica_comanda", null, "add_comanda_edit");
    
    ?>
        <script type="text/javascript">
        
            function seteazaHidden() {
                document.getElementById('id_contact_exec_aux_hidden').value = document.getElementById('id_contact_exec').value;    
            }
            
            function checkAdrese() {
                if (document.getElementById('IncarcareCount').innerHTML == '0' 
                    || document.getElementById('DescarcareCount').innerHTML == '0') {
                    alert(LANG_minim_o_adresa_de_incarcare_si_una_de_descarcare);
                    return false;
                }
                else
                    return true; 
            }
            
            function checkFirme() {
                if (document.form1.id_firma_sol.value == document.form1.id_firma_exec.value) {
                    alert(LANG_firmele_de_incarcare_si_descarcare_trebuie_sa_fie_diferite);
                    return false;
                }
                else
                    return true; 
            }
            
            function checkDates() {
				var data_incarcarii = document.form1.data_incarcarii.value;
				var data1 = getDateFromText(data_incarcarii);
				var data_descarcarii = document.form1.data_descarcarii.value;
				var data2 = getDateFromText(data_descarcarii);
				if (data1 > data2) {
					alert(LANG_Data_incarcarii_inainte_de_data_descarcarii);
                    return false;
				}
				return true;
            }
        
            function validateForm() {
                return (validatePrintable(document.form1.nr_referinta_sol.value, '<?php echo LANG_Numar_referinta; ?>', true, 1) &&
                            validatePrintable(document.form1.data_comanda_sol.value, '<?php echo LANG_Data_comenzii; ?>', true, 1) &&
                            validateFloat(prepareNumberForServer(document.form1.suma_sol.value), '<?php echo LANG_Suma_sol; ?>', true) &&                    
                            validateFloat(prepareNumberForServer(document.form1.suma_totala_sol.value), '<?php echo LANG_Suma_totala_sol; ?>', true) &&                    
                            validateInteger(document.form1.zile_scadenta_sol.value, '<?php echo LANG_Zile_scadenta_sol; ?>', true) &&                    
                                                        
                            validatePrintable(document.form1.nr_comanda_exec.value, '<?php echo LANG_Nr_comanda_exec; ?>', true, 1) &&
                            validatePrintable(document.form1.data_comenzii.value, '<?php echo LANG_Data_comenzii; ?>', true, 1) &&
                            validateFloat(prepareNumberForServer(document.form1.suma_exec.value), '<?php echo LANG_Suma_exec; ?>', true) &&                    
                            validateFloat(prepareNumberForServer(document.form1.suma_totala_exec.value), '<?php echo LANG_Suma_totala_exec; ?>', true) &&                    
                            validateInteger(document.form1.zile_scadenta_exec.value, '<?php echo LANG_Zile_scadenta_exec; ?>', true) &&
                            
                            validatePrintable(document.form1.fel_camion.value, '<?php echo LANG_Fel_camion; ?>', true, 1) &&                           
//                            checkDates() &&
                            checkAdrese() &&
                            checkFirme() &&
                            
                            validatePrintable(document.form1.nr_factura_sol.value, '<?php echo LANG_nr_factura_sol; ?>', false, 1) &&
                            validateFloat(prepareNumberForServer(document.form1.taxe_supl_to_sol.value), '<?php echo LANG_taxe_supl_to_sol; ?>', false) &&
                            validateFloat(prepareNumberForServer(document.form1.penaliz_from_sol.value), '<?php echo LANG_Penalizare_from_sol; ?>', false) &&
                            validatePrintable(document.form1.coment_sol.value, '<?php echo LANG_Coment_sol; ?>', false, 1) &&
                            validatePrintable(document.form1._text_alte_acte_sol.value, '<?php echo LANG_Alte_acte_sol; ?>', false, 1) &&
                            
                            validatePrintable(document.form1.nr_factura_exec.value, '<?php echo LANG_nr_factura_exec; ?>', false, 1) &&
                            validateFloat(prepareNumberForServer(document.form1.taxe_supl_from_exec.value), '<?php echo LANG_taxe_supl_from_exec; ?>', false) &&
                            validateFloat(prepareNumberForServer(document.form1.penaliz_to_exec.value), '<?php echo LANG_Penalizare_to_exec; ?>', false) &&
                            validatePrintable(document.form1.coment_exec.value, '<?php echo LANG_Coment_exec; ?>', false, 1) &&
                            validatePrintable(document.form1._text_alte_acte_exec.value, '<?php echo LANG_Alte_acte_exec; ?>', false, 1) &&
                            
                            validatePrintable(document.form1.nr_inmatriculare.value, '<?php echo LANG_nr_inmatriculare ?>', false, 1) &&
                            validatePrintable(document.form1.nume_sofer.value, '<?php echo LANG_Nume_sofer; ?>', false, 1) &&
                            validatePhone(document.form1.tel_sofer.value, '<?php echo LANG_Telefon_sofer; ?>', false) )
                            ;
            }
        </script>
    <?php    
    if ($_SESSION['comanda']->id_comanda == CT_NOT_SAVED_YET)
		$text = LANG_Adauga_comanda;
	else
		$text = LANG_Modifica_comanda;
		
	$linkuri = array(LANG_Home => "home.php", LANG_Comenzi => "show_comenzi.php", $text => "");    
    
	titlu_pagina($linkuri);
    output_error_msg();
    output_notice_msg();
    output_extra_text(LANG_EXTRA_ADD_COMANDA);
?>
	
	<div style="padding: 0px" class="container">
	<form id="form1" name="form1" method="post" action="add_comanda.php" onsubmit="return validateForm();">
	
    <table width="100%">
    
	<tr class="capTabel">
	<td width="50%" valign="top">
	<fieldset>
		<legend><?php echo LANG_DATE_SOLICITANT; ?></legend>
		<table  width="100%" cellpadding="0" cellspacing="2" border="0">
			<tr>
			  <td <?php check_field('id_firma_sol'); ?>><?php echo LANG_Firma_sol ." " . CT_OBLIGATORIU; ?></td>
			  <td colspan="3">
			  	<span id="firme_sol_select">
				  	<?php 
					  try {
				  		$var = Firma::queryLoadByClientWithName($db, $id_client);
				  		$selected = render_firme_comanda_show_contact("id_firma_sol", $var, $_SESSION['comanda']->id_firma_sol, 'contact_sol');  
					  }
					  catch (QueryLoadFirmaException $e) {
					  	redirectOnError(CT_ADD_COMANDA_FIRMA_LOAD_BY_CLIENT_WITH_NAME);				  	
					  }
					?>
				</span>
				<input onclick="javascript: show_modal_firma_from_comanda('firme_sol_select', 'firme_exec_select', 280, 220, 'add', 'id_firma_sol')" type="button" value=" + " id="add_firma_sol_but" name="add_firma_sol_but" />
				<a style="cursor:pointer" onclick="javascript: show_modal_firma_from_comanda('firme_sol_select', 'firme_exec_select', 280, 220, 'edit', 'id_firma_sol');"><?php echo '<img border="0" src="' . IMG_PATH .  "select_field.png" . '"/>'; ?></a>
			  </td>
			</tr>
			<tr>
			  <td <?php check_field('id_contact_sol'); ?>><?php echo LANG_Contact_sol; ?></td>
			  <td colspan="3">
			  	<span id="contact_sol">
				  	<?php
				  		if (isset($var[$selected]->id_firma))
				  			render_contact_select_comanda($var[$selected]->id_firma, $_SESSION['comanda']->id_contact_sol, $db, "id_contact_sol");
				  		else 
				  			render_contact_select_comanda(null, $_SESSION['comanda']->id_contact_sol, $db, "id_contact_sol");
				  	?>
			  	</span>
				<input onclick="javascript: show_modal_contact_from_comanda('contact_sol', 240, 190, 'add', 'id_contact_sol')" type="button" value=" + " id="add_contact_sol_but" name="add_contact_sol_but" />
				<a style="cursor:pointer" onclick="javascript: show_modal_contact_from_comanda('contact_sol', 240, 190, 'edit', 'id_contact_sol');"><?php echo '<img border="0" src="' . IMG_PATH .  "select_field.png" . '"/>'; ?></a>
			  </td>
			</tr>
			<tr>
			  <td <?php check_field('nr_comanda_sol'); ?>><?php echo LANG_Numar_comanda_sol; ?></td>
			  <td><input <?php echo show_tooltip(LANG_Numar_comanda_sol_tooltip); ?> 
                    type="text" name="nr_comanda_sol" class="input_numar_comanda" value="<?php echo $_SESSION['comanda']->nr_comanda_sol ?>"
                    maxlength="<?php echo CT_MAX_NR_COMANDA_LENGTH ?>"/>
              </td>
              <td  colspan="2">
                  <?php echo '<span '; check_field('data_comanda_sol'); echo ">".LANG_Din. " " . CT_OBLIGATORIU . " </span>"; ?>
                  
                  <?php echo render_date_field_button($_SESSION['comanda']->data_comanda_sol, 'data_comanda_sol', 'main'); ?>
			  </td>
            </tr>
			<tr>
              <td <?php check_field('nr_factura_sol'); ?>><?php echo LANG_Numar_factura_sol; ?></td>
              <td><input <?php echo show_tooltip(LANG_Numar_factura_tooltip_sol); ?> 
                    type="text" name="nr_factura_sol" class="input_numar_comanda" value="<?php echo $_SESSION['comanda']->nr_factura_sol ?>"
                    maxlength="<?php echo CT_MAX_NR_FACTURA_LENGTH ?>"/>
                    <?php if ($_SESSION['comanda']->id_comanda != CT_NOT_SAVED_YET)
                            echo '<a style="cursor:pointer" onclick="javascript: show_factura_din_comanda('.$_SESSION['comanda']->id_comanda.');"><img border="0" src="'.IMG_PATH.'select_field.png"/></a>'; ?>
              </td>
              <td  colspan="2">
                  <?php echo '<span '; check_field('data_factura_sol'); echo ">".LANG_Din. "&nbsp;&nbsp; </span>"; ?>
                  
                  <?php echo render_date_field_button($_SESSION['comanda']->data_factura_sol, 'data_factura_sol', 'main'); ?>
              </td>
            </tr>
            <tr>
                <td <?php check_field('nr_referinta_sol'); ?>><?php echo LANG_Numar_referinta . CT_OBLIGATORIU; ?></td>
              <td><input <?php echo show_tooltip(LANG_Numar_referinta_sol_tooltip); ?> 
                    type="text" name="nr_referinta_sol" class="input_numar_comanda" value="<?php echo $_SESSION['comanda']->nr_referinta_sol ?>"
                    maxlength="<?php echo CT_MAX_NR_COMANDA_LENGTH ?>"/>
              </td>
                <td>
                    <?php echo LANG_Pret_pe_km; ?>
                </td>
                <td>
                    <?php 
                        if ($_SESSION['comanda']->nr_km != 0) {
                            $pret_pe_km = round($_SESSION['comanda']->suma_sol / $_SESSION['comanda']->nr_km, 2);
                            $pret_pe_km = prepareFloatForUser($pret_pe_km);
                        }
                        else
                            $pret_pe_km = '';
                        echo '<span id="pret_pe_km_sol">'. $pret_pe_km .'</span>'; ?>
                </td>
            </tr>
            <tr>
			  <td <?php check_field('suma_sol'); ?>><?php echo LANG_Suma_sol." " . CT_OBLIGATORIU; ?></td>
			  <td><input <?php echo show_tooltip(LANG_Suma_sol_tooltip); ?> 
              type="text" name="suma_sol" class="input_number" value="<?php echo prepareFloatForUser($_SESSION['comanda']->suma_sol); ?>" 
              onchange="javascript: calc_total_sol(); calc_pret_pe_km();" maxlength="<?php echo CT_MAX_NUMBER_LENGTH ?>"/></td>
			  <td <?php check_field('taxe_supl_to_sol'); ?>><?php echo LANG_Taxa_suplimentara_to_sol; ?></td>
			  <td><input <?php echo show_tooltip(LANG_Taxa_suplimentara_to_sol_tooltip); ?> 
              type="text" name="taxe_supl_to_sol" class="input_number" value="<?php echo prepareFloatForUser($_SESSION['comanda']->taxe_supl_to_sol); ?>" 
              onchange="javascript: calc_total_sol();" maxlength="<?php echo CT_MAX_NUMBER_LENGTH ?>" /></td>
			</tr>
			<tr>
			  <td <?php check_field('penaliz_from_sol'); ?>><?php echo LANG_Penalizare_from_sol; ?></td>
			  <td><input <?php echo show_tooltip(LANG_Penalizare_from_sol_tooltip); ?> 
              type="text" name="penaliz_from_sol" class="input_number" value="<?php echo prepareFloatForUser($_SESSION['comanda']->penaliz_from_sol); ?>" 
              onchange="javascript: calc_total_sol();" maxlength="<?php echo CT_MAX_NUMBER_LENGTH ?>" /></td>
			  <td <?php check_field('suma_totala_sol'); ?>><?php echo LANG_Suma_totala_sol; ?></td>
			  <td><input type="text" readonly name="suma_totala_sol" class="input_number" 
              maxlength="<?php echo CT_MAX_NUMBER_LENGTH ?>" value="<?php echo prepareFloatForUser($_SESSION['comanda']->suma_totala_sol); ?>"/></td>
			</tr>
			<tr>
			  <td <?php check_field('data_tr_acte_sol'); ?>><?php echo LANG_Data_tr_acte_sol; ?></td>
			  <td>
                <?php echo render_date_field_button($_SESSION['comanda']->data_tr_acte_sol, 'data_tr_acte_sol', 'main', 'calc_data_scadenta_sol();'); ?>
			  </td>
              <td <?php check_field('zile_scadenta_sol'); ?>><?php echo LANG_Zile_scadenta . CT_OBLIGATORIU; ?></td>
              <td><input <?php echo show_tooltip(LANG_Zile_scadenta_tooltip); ?> type="text" name="zile_scadenta_sol" 
              class="input_number" value="<?php  echo $_SESSION['comanda']->zile_scadenta_sol; ?>" 
              onBlur="calc_data_scadenta_sol();" maxlength="<?php echo CT_MAX_NUMBER_LENGTH ?>" /></td>
            </tr>
            <tr>
                <td><?php echo '<span '; check_field('data_scadenta_sol'); echo ">".LANG_Data_scadenta_sol."</span>";?></td>
                <td>
                    <?php echo render_date_field_button($_SESSION['comanda']->data_scadenta_sol, 'data_scadenta_sol', 'main'); ?>
                </td>
                <td><?php echo '<span '; check_field('moneda_sol'); echo ">".LANG_Moneda_sol.": </span>"; ?></td>
                <td colspan="3"><?php render_combobox("moneda_sol", $monede_int, $currencies, $_SESSION['comanda']->moneda_sol); ?></td>
            </tr>
			<tr>
			  <td <?php check_field('coment_sol'); ?>><?php echo LANG_Coment_sol; ?></td>
			  <td colspan="3"><textarea <?php echo show_tooltip(LANG_Coment_sol_tooltip); ?> name="coment_sol" class="input_textarea" rows="1" cols="15"><?php echo $_SESSION['comanda']->coment_sol ?></textarea></td>
			</tr>
			<tr>
			<td colspan="4">
			<table>
				<tr>
					<td>
						<?php echo LANG_ACTE_NECESARE; ?>
					</td>
					<td>
						<?php render_checkbox_act_necesar($_SESSION['comanda'], '_cmr_sol', LANG_CMR_sol); ?>
				  	</td>
					<td>
						<?php render_checkbox_act_necesar($_SESSION['comanda'], '_factura_sol', LANG_Factura_sol); ?>
					</td>
					<td>
						<?php render_checkbox_act_necesar($_SESSION['comanda'], '_carnet_tir_sol', LANG_Carnet_tir_sol); ?>
					</td>
					<td>
						<?php render_checkbox_act_necesar($_SESSION['comanda'], '_decl_vamala_sol', LANG_Declaratie_vamala_sol); ?>
					</td>
					<td>
						<?php render_checkbox_act_necesar($_SESSION['comanda'], '_alte_acte_sol', LANG_Alte_acte_sol); ?>
					</td>					
				</tr>
				<tr>
					<td>
						<?php echo LANG_ACTE_TRIMISE; ?>
					</td>
				  <td>
				  	<?php render_checkbox_act_trimis($_SESSION['comanda'], '_cmr_sol', LANG_CMR_sol); ?>
				  </td>				  
				  <td>
				  	<?php render_checkbox_act_trimis($_SESSION['comanda'], '_factura_sol', LANG_Factura_sol); ?>
				  </td>				  
				  <td>
				  	<?php render_checkbox_act_trimis($_SESSION['comanda'], '_carnet_tir_sol', LANG_Carnet_tir_sol); ?>
				  </td>				  
				  <td>
				  	<?php render_checkbox_act_trimis($_SESSION['comanda'], '_decl_vamala_sol', LANG_Declaratie_vamala_sol); ?>
				  </td>
				  <td>
				  	<?php render_checkbox_act_trimis($_SESSION['comanda'], '_alte_acte_sol', LANG_Alte_acte_sol); ?>
				  </td>
				</tr>
				<tr>
				  <td <?php check_field('_text_alte_acte_sol'); ?>><?php echo LANG_Text_alte_acte_sol; ?></td>
				  <td colspan="5"><textarea <?php echo show_tooltip(LANG_Alte_acte_sol_tooltip); ?> name="_text_alte_acte_sol" id="_text_alte_acte_sol" class="input_textarea" rows="1" cols="55" maxlength="<?php echo CT_MAX_TEXT2_LENGTH ?>"><?php echo $_SESSION['comanda']->_text_alte_acte_sol ?></textarea></td>
				</tr>
			</table>
			</td>
			</tr>
		</table>
	</fieldset>
	</td>
	<td width="50%" valign="top">
	<fieldset>
		<legend><?php echo LANG_DATE_EXECUTANT; ?></legend>
		<table width="100%"  cellpadding="0" cellspacing="2" border="0">
            <tr>
              <td <?php check_field('id_firma_exec'); ?>><?php echo LANG_Firma_exec ." " . CT_OBLIGATORIU; ?></td>
              <td colspan="3">
              	<span id="firme_exec_select">
                  	<?php 
	                  try {
	                      $var = Firma::queryLoadByClientWithName($db, $id_client);                                                     
	                      $selected = render_firme_comanda_show_contact("id_firma_exec", $var, $_SESSION['comanda']->id_firma_exec, 'contact_exec');  
	                  }
	                  catch (QueryLoadFirmaException $e) {
	                      redirectOnError(CT_ADD_COMANDA_FIRMA_LOAD_BY_CLIENT_WITH_NAME);                      
	                  }
                	?>
                </span>
				<input onclick="javascript: show_modal_firma_from_comanda('firme_sol_select', 'firme_exec_select', 280, 220, 'add', 'id_firma_exec')" type="button" value=" + " id="add_firma_exec_but" name="add_firma_exec_but" />
				<a style="cursor:pointer" onclick="javascript: show_modal_firma_from_comanda('firme_sol_select', 'firme_exec_select', 280, 220, 'edit', 'id_firma_exec');"><?php echo '<img border="0" src="' . IMG_PATH .  "select_field.png" . '"/>'; ?></a>
              </td>
            </tr>
            <tr>
              <td <?php check_field('id_contact_exec'); ?>><?php echo LANG_Contact_exec; ?></td>
              <td colspan="3">
              	<span id="contact_exec">
                  <?php
                  	if (isset($var[$selected]->id_firma))	 
						render_contact_select_comanda($var[$selected]->id_firma, $_SESSION['comanda']->id_contact_exec, $db, "id_contact_exec");
					else 
						render_contact_select_comanda(null, $_SESSION['comanda']->id_contact_exec, $db, "id_contact_exec");
                  ?>
                </span>
				<input onclick="javascript: show_modal_contact_from_comanda('contact_exec', 240, 190, 'add', 'id_contact_exec')" type="button" value=" + " id="add_contact_exec_but" name="add_contact_exec_but" />
				<a style="cursor:pointer" onclick="javascript: show_modal_contact_from_comanda('contact_exec', 240, 190, 'edit', 'id_contact_exec');"><?php echo '<img border="0" src="' . IMG_PATH .  "select_field.png" . '"/>'; ?></a>
              </td>
            </tr>
			<tr>
			  <td <?php check_field('nr_comanda_exec'); ?>><?php echo LANG_Numar_comanda." " . CT_OBLIGATORIU; ?></td>
			  <td><input <?php echo show_tooltip(LANG_Numar_comanda_tooltip); ?> 
					type="text" name="nr_comanda_exec" class="input_numar_comanda" 
					value="<?php echo $_SESSION['comanda']->nr_comanda_exec ?>" maxlength="<?php echo CT_MAX_NR_COMANDA_LENGTH ?>" />
              </td>
              <td colspan="2">
			  	<?php echo '<span '; check_field('data_comenzii'); echo ">".LANG_Din." " . CT_OBLIGATORIU . " </span>"; ?>			  		
				
                <?php echo render_date_field_button($_SESSION['comanda']->data_comenzii, 'data_comenzii', 'main'); ?>
			  </td>
			</tr>
			<tr>
              <td <?php check_field('nr_factura_exec'); ?>><?php echo LANG_Numar_factura_exec; ?></td>
              <td><input <?php echo show_tooltip(LANG_Numar_factura_exec_tooltip); ?> 
					type="text" name="nr_factura_exec" class="input_numar_comanda" 
					value="<?php echo $_SESSION['comanda']->nr_factura_exec ?>" maxlength="<?php echo CT_MAX_NR_FACTURA_LENGTH ?>" />
              </td>
              <td colspan="2">
                  <?php echo '<span '; check_field('data_factura_exec'); echo ">".LANG_Din."&nbsp;&nbsp; </span>"; ?>
                  
                  <?php echo render_date_field_button($_SESSION['comanda']->data_factura_exec, 'data_factura_exec', 'main'); ?>
              </td>
            </tr>
            <tr>
                <td <?php check_field('tva_inclus_exec'); ?>><?php echo LANG_TVA_inclus; ?></td>
                <td>
                    <?php
                        if ($_SESSION['comanda']->tva_inclus_exec == CT_TVA_INCLUS_EXEC)
                            $text = 'checked="checked"';
                        else
                            $text = '';
                    ?>
                    <input type="checkbox" <?php echo $text; ?> name="tva_inclus_exec" value="1"/>
                </td>
                <td>
                    <?php echo LANG_Pret_pe_km; ?>
                </td>
                <td>
                    <?php 
                        if ($_SESSION['comanda']->nr_km != 0) {
                            $pret_pe_km = round($_SESSION['comanda']->suma_exec / $_SESSION['comanda']->nr_km, 2);
                            $pret_pe_km = prepareFloatForUser($pret_pe_km);
                        }
                        else
                            $pret_pe_km = '';
                        echo '<span id="pret_pe_km_exec">'. $pret_pe_km .'</span>'; ?>
                </td>
            </tr>
            <tr>
				<td <?php check_field('suma_exec'); ?>><?php echo LANG_Suma_exec." " . CT_OBLIGATORIU; ?></td>
				<td><input <?php echo show_tooltip(LANG_Suma_exec_tooltip); ?> 
                    type="text" name="suma_exec" class="input_number" value="<?php echo prepareFloatForUser($_SESSION['comanda']->suma_exec); ?>" 
                    onchange="javascript: calc_total_exec(); calc_pret_pe_km();" maxlength="<?php echo CT_MAX_NUMBER_LENGTH ?>" /></td>
				<td <?php check_field('taxe_supl_from_exec'); ?>><?php echo LANG_Taxa_suplimentara_from_exec; ?></td>
				<td><input <?php show_tooltip(LANG_Taxa_suplimentara_from_exec); ?> 
                    type="text" name="taxe_supl_from_exec" class="input_number" value="<?php echo prepareFloatForUser($_SESSION['comanda']->taxe_supl_from_exec); ?>" 
                    onchange="javascript: calc_total_exec();" maxlength="<?php echo CT_MAX_NUMBER_LENGTH ?>" /></td>
			</tr>
			<tr>
				<td <?php check_field('penaliz_to_exec'); ?>><?php echo LANG_Penalizare_to_exec; ?></td>
				<td><input <?php echo show_tooltip(LANG_Penalizare_to_exec_tooltip); ?> 
                type="text" name="penaliz_to_exec" class="input_number" value="<?php echo prepareFloatForUser($_SESSION['comanda']->penaliz_to_exec); ?>" 
                onchange="javascript: calc_total_exec();" maxlength="<?php echo CT_MAX_NUMBER_LENGTH ?>" /></td>
				<td <?php check_field('suma_totala_exec'); ?>><?php echo LANG_Suma_totala_exec; ?></td>
				<td><input <?php echo show_tooltip(LANG_Suma_totala_exec_tooltip); ?> 
                    type="text" readonly name="suma_totala_exec" class="input_number" 
                    value="<?php echo prepareFloatForUser($_SESSION['comanda']->suma_totala_exec); ?>" maxlength="<?php echo CT_MAX_NUMBER_LENGTH ?>" /></td>
			</tr>
			<tr>
			  <td <?php check_field('data_primirii_acte_exec'); ?>><?php echo LANG_data_primirii_acte_exec; ?></td>
			  <td>
			    <?php echo render_date_field_button($_SESSION['comanda']->data_primirii_acte_exec, 'data_primirii_acte_exec', 'main', 'calc_data_scadenta_exec();'); ?>
			  </td>
              <td <?php check_field('zile_scadenta_exec'); ?>><?php echo LANG_Zile_scadenta . CT_OBLIGATORIU; ?></td>
              <td><input <?php echo show_tooltip(LANG_Zile_scadenta_tooltip); ?> 
                type="text" name="zile_scadenta_exec" class="input_number" value="<?php echo $_SESSION['comanda']->zile_scadenta_exec; ?>" 
                onBlur="calc_data_scadenta_exec();" maxlength="<?php echo CT_MAX_NUMBER_LENGTH ?>" /></td>  
			</tr>
			<tr>
              <td><?php echo '<span '; check_field('data_scadenta_exec'); echo ">".LANG_Data_scadenta_exec . "</span>"; ?></td>
              <td>
                <?php echo render_date_field_button($_SESSION['comanda']->data_scadenta_exec, 'data_scadenta_exec', 'main'); ?>
              </td>
			  <td <?php check_field('moneda_exec'); ?>><?php echo LANG_Moneda_exec; ?></td>
			  <td><?php render_combobox("moneda_exec", $monede_int, $currencies, $_SESSION['comanda']->moneda_exec); ?></td>
			</tr>	
			<tr>
			  <td <?php check_field('coment_exec'); ?>><?php echo LANG_Coment_exec; ?></td>
			  <td colspan="3"><textarea <?php echo show_tooltip(LANG_Coment_exec_tooltip); ?> 
                name="coment_exec" class="input_textarea" rows="" 
                cols="15" maxlength="<?php echo CT_MAX_TEXT_LENGTH ?>" ><?php echo $_SESSION['comanda']->coment_exec ?></textarea></td>
			</tr>
			<tr>
			<td colspan="4">
			<table>
				<tr>
					<td>
						<?php echo LANG_ACTE_NECESARE; ?>
					</td>
					<td><?php render_checkbox_act_necesar($_SESSION['comanda'], '_cmr_exec', LANG_CMR_exec); ?></td>
					<td><?php render_checkbox_act_necesar($_SESSION['comanda'], '_factura_exec', LANG_Factura_exec); ?></td>
				  	<td><?php render_checkbox_act_necesar($_SESSION['comanda'], '_carnet_tir_exec', LANG_Carnet_tir_exec); ?></td>
				  	<td><?php render_checkbox_act_necesar($_SESSION['comanda'], '_decl_vamala_exec', LANG_Declaratie_vamala_exec); ?></td>
				  	<td><?php render_checkbox_act_necesar($_SESSION['comanda'], '_alte_acte_exec', LANG_Alte_acte_exec); ?></td>				  
				</tr>
				<tr>
					<td>
						<?php echo LANG_ACTE_PRIMITE; ?>
					</td>
				  <td><?php render_checkbox_act_trimis($_SESSION['comanda'], '_cmr_exec', LANG_CMR_exec); ?></td>
				  <td><?php render_checkbox_act_trimis($_SESSION['comanda'], '_factura_exec', LANG_Factura_exec); ?></td>
				  <td><?php render_checkbox_act_trimis($_SESSION['comanda'], '_carnet_tir_exec', LANG_Carnet_tir_exec); ?></td>
				  <td><?php render_checkbox_act_trimis($_SESSION['comanda'], '_decl_vamala_exec', LANG_Declaratie_vamala_exec); ?></td>
				  <td><?php render_checkbox_act_trimis($_SESSION['comanda'], '_alte_acte_exec', LANG_Alte_acte_exec); ?></td>
				</tr>
				<tr>
				  <td <?php check_field('_text_alte_acte_exec'); ?>><?php echo LANG_Text_alte_acte_exec; ?></td>
				  <td colspan="5"><textarea <?php echo show_tooltip(LANG_Alte_acte_exec_tooltip); ?> name="_text_alte_acte_exec" id="_text_alte_acte_exec" class="input_textarea" 
                  rows="1" cols="55" maxlength="<?php echo CT_MAX_TEXT2_LENGTH ?>" ><?php echo $_SESSION['comanda']->_text_alte_acte_exec ?></textarea></td>
				</tr>
			</table>
			</td>
			</tr>
		</table>	
	</fieldset>
	</td>
	</tr>
	</table>
	
	<div class="container">
		<div style="padding: 0px" class="capTabel">
		
		  <table width="100%" border="0" cellspacing="2" cellpadding="1">	  	
			<tr>
	            <td>
	                <fieldset>
	                    <legend><?php echo LANG_DATE_COMANDA; ?></legend>        
	    
	            <table width="100%" border="0" >
			<tr>
				<td colspan="4">
					<table>
					<tr>
	                    <td <?php check_field('interna_externa'); ?>><?php echo LANG_Tip_comanda; ?></td>
	                    <td>
	                        <?php
	                            $comanda_int_ext = array(CT_COMANDA_INTERNA => constant("LANG_Comanda_interna"), CT_COMANDA_EXTERNA => constant("LANG_Comanda_externa"));
	                            render_combobox("interna_externa", array_keys($comanda_int_ext), $comanda_int_ext, $_SESSION['comanda']->interna_externa); 
	                        ?>
	                    </td>
	                  <td <?php check_field('nr_km'); ?>><?php echo LANG_Nr_km; ?></td> 
	                  <td><input <?php echo show_tooltip(LANG_Nr_km_tooltip); ?> 
	                    type="text" name="nr_km" class="input_number" onchange="javascript: calc_pret_pe_km();"
	                    value="<?php echo prepareIntForUser($_SESSION['comanda']->nr_km) ?>" maxlength="<?php echo CT_MAX_NUMBER_LENGTH ?>" /></td>
	                  <td <?php check_field('fel_camion'); ?>><?php echo LANG_Fel_camion . CT_OBLIGATORIU; ?></td> 
	                  <td><input <?php echo show_tooltip(LANG_Fel_camion_tooltip); ?> 
	                    type="text" name="fel_camion" class="input_text" 
	                    value="<?php echo $_SESSION['comanda']->fel_camion ?>" maxlength="<?php echo CT_MAX_FEL_CAMION_LENGTH ?>" /></td>
	                  <td <?php check_field('nr_inmatriculare'); ?>><?php echo LANG_Numar_inmatriculare; ?></td>
	                  <td><input <?php echo show_tooltip(LANG_Numar_inmatriculare_tooltip); ?> 
	                    type="text" name="nr_inmatriculare" class="input_text" 
	                    value="<?php echo $_SESSION['comanda']->nr_inmatriculare ?>" maxlength="<?php echo CT_MAX_NR_INMATRICULARE_LENGTH ?>" /></td>
	                  <td <?php check_field('nume_sofer'); ?>><?php echo LANG_Nume_sofer; ?></td>
	                  <td><input <?php echo show_tooltip(LANG_Nume_sofer_tooltip); ?> 
	                    type="text" name="nume_sofer" class="input_text" 
	                    value="<?php echo $_SESSION['comanda']->nume_sofer ?>" maxlength="<?php echo CT_MAX_NUME_LENGTH ?>" /></td>
	            
					  <td <?php check_field('tel_sofer'); ?>><?php echo LANG_Telefon_sofer; ?></td>
	                  <td><input <?php echo show_tooltip(LANG_Telefon_sofer_tooltip); ?> 
	                    type="text" name="tel_sofer" class="input_tel" 
	                    value="<?php echo $_SESSION['comanda']->tel_sofer ?>" maxlength="<?php echo CT_MAX_PHONE_LENGTH ?>" /></td>
					</tr>
	                <tr>
	                    <td <?php check_field('status'); ?>><?php echo LANG_Status; ?></td>
	                    <td colspan="11">
	                        <textarea name="status" maxlength="<?php echo CT_MAX_TEXT2_LENGTH ?>" class="input_textarea" <?php echo show_tooltip(LANG_Status_tooltip); ?>><?php echo $_SESSION['comanda']->status; ?></textarea>
	                    </td>
	                </tr>
					</table>
				</td>
			</tr>
			
		  	<tr>
	             <td valign="top" width="50%">
	                 <div id="incarcare">                 
	                     <?php render_adresa($_SESSION['comanda'], CT_ADRESA_COMANDA_INCARCARE, CT_ADRESA_COMANDA, 'incarcare'); ?>
	                 </div>
	                 <div id="mainContainer3">
	                     <input type="button" onclick="javascript:arata_modal_adresa('incarcare',<?php echo CT_ADRESA_COMANDA; ?>, <?php echo CT_ADRESA_COMANDA_INCARCARE; ?>, 'true');" value="<?php echo LANG_Add_adresa_incarcare; ?>" />
	                 </div>
	             </td>
	             <td valign="top" width="50%">
	                 <div id="descarcare">    
	                     <?php render_adresa($_SESSION['comanda'], CT_ADRESA_COMANDA_DESCARCARE, CT_ADRESA_COMANDA, 'descarcare'); ?>
	                 </div>
	                 <div id="mainContainer4">                 
	                     <input type="button" onclick="javascript:arata_modal_adresa('descarcare',<?php echo CT_ADRESA_COMANDA; ?>, <?php echo CT_ADRESA_COMANDA_DESCARCARE; ?>, 'false');" value="<?php echo LANG_Add_adresa_descarcare; ?>" />
	                 </div>
	             </td>
	        </tr>
	        <tr>
	            <td valign="top" width="50%">
	                 <div id="vama_export">    
	                     <?php render_adresa($_SESSION['comanda'], CT_ADRESA_COMANDA_VAMA_EXPORT, CT_ADRESA_COMANDA, 'vama_export'); ?>
	                 </div>
	                 <div id="mainContainer2">
	                     <input type="button" onclick="javascript: arata_modal_adresa('vama_export',<?php echo CT_ADRESA_COMANDA; ?>, <?php echo CT_ADRESA_COMANDA_VAMA_EXPORT; ?>, 'false');" value="<?php echo LANG_Add_vama_export; ?>" />
	                 </div>
	             </td>
			 	<td valign="top" width="50%">
				 	<div id="vama_import">
				 		<?php render_adresa($_SESSION['comanda'], CT_ADRESA_COMANDA_VAMA_IMPORT, CT_ADRESA_COMANDA, 'vama_import'); ?>
				 	</div>
				 	<div id="mainContainer1">
		 				<input type="button" onclick="javascript: arata_modal_adresa('vama_import',<?php echo CT_ADRESA_COMANDA; ?>, <?php echo CT_ADRESA_COMANDA_VAMA_IMPORT; ?>, 'false');" value="<?php echo LANG_Add_vama_import; ?>" />
				 	</div>
			 	</td>
			</tr> 			
			
	        </table>
	        
	        </fieldset>   
	        </td>
	        </tr>      
	        <tr>
	            <td colspan="4" align="center">
	                <?php    
	                    if ($_SESSION['comanda']->id_comanda == CT_NOT_SAVED_YET)
	                        buton_final_ok(LANG_Adauga_comanda, "post_comanda");
	                    else
	                        buton_final_ok(LANG_Modifica_comanda, "post_comanda");
	                    echo '&nbsp;&nbsp;';
	                    buton_final_cancel(LANG_CANCEL, "show_comenzi.php");
	                ?>
	            </td>
	        </tr>
		  </table>	  
	      
	      <input type="hidden" name="id_contact_exec_aux_hidden" id="id_contact_exec_aux_hidden" value="-1" />
	      <input type="hidden" name="id_comanda" id="id_comanda" value="<?php echo $_SESSION['comanda']->id_comanda; ?>" />
	      
		</div>
	
	</div>
	</form>
	</div>
	<script type="text/javascript">
		set_buton_visible_invisible_add_comanda();				
	</script>
<?php
	}
	unset($_SESSION['wrong_ids']); 

    html_footer();
?>